import React, { Component } from 'react'
import { Toast } from 'antd-mobile'
import axios from 'axios'
import Header from '../../components/Header'
import './index.scss'
import { getLocalCity } from '../../utils/localCity'
import { List, AutoSizer } from 'react-virtualized'

export default class CityList extends Component {
  state = {
    cityList: {},
    cityIndex: [],
    activeItem: 0
  }

  haveCityList = ['北京', '上海', '广州', '深圳']

  listRef = React.createRef()

  async componentDidMount() {
    await this.getCityList()

    this.listRef.current && this.listRef.current.measureAllRows()
  }

  handleData = (data) => {
    const cityList = {}

    data.forEach(item => {
      let firstVar = item.short.substr(0, 1)

      if (cityList[firstVar]) {
        cityList[firstVar].push(item)
      } else {
        cityList[firstVar] = [item]
      }
    })

    const cityIndex = Object.keys(cityList).sort()

    return {
      cityList,
      cityIndex
    }
  }

  getCityList = async () => {
    const { data } = await axios.get('http://127.0.0.1:8080/area/city?level=1')
    const { cityList, cityIndex } = this.handleData(data.body)

    const { data: hotData } = await axios.get('http://127.0.0.1:8080/area/hot')
    cityList.hot = hotData.body
    cityIndex.unshift('hot')

    const localData = await getLocalCity()
    cityList['#'] = [localData]
    cityIndex.unshift('#')

    this.setState({
      cityIndex,
      cityList
    })

  }

  handleTitle = (title) => {
    if(title === '#') {
      return '当前城市'
    } else if (title === 'hot') {
      return '热门城市'
    } else {
      return title.toUpperCase()
    }
  }

  renderHeader() {
    return (
      <Header title="城市列表" />
    )
  }

  changeCity = (label, value) => {
    if(this.haveCityList.includes(label)) {
      localStorage.setItem('local_city', JSON.stringify({label, value}))
      this.props.history.go(-1)
    } else {
      Toast.fail('该城市暂未开通!!!', 1)
    }
  }

  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) => {
    const title = this.state.cityIndex[index]
    const arr = this.state.cityList[title]

    return (
      <div className="item-box" key={key} style={style}>
        <div className="item-box-title">{this.handleTitle(title)}</div>
        {
          arr.map(item => {
            return <div className="item-box-label" key={item.value} onClick={()=>this.changeCity(item.label, item.value)}>{item.label}</div>
          })
        }
      </div>
    );
  }

  rowHeight = ({index}) => {
    const key = this.state.cityIndex[index]
    const height = 36 + 50 * this.state.cityList[key].length

    return height
  }

  onRowsRendered = ({ startIndex }) => {
    if(this.state.activeItem === startIndex) {
      return 
    }
    this.setState({
      activeItem: startIndex
    })
  }

  renderCityList = () => {
    return (
      <AutoSizer>
        {({ height, width }) => (
          <List
            ref={this.listRef}
            width={width}
            height={height}
            rowCount={this.state.cityIndex.length}
            rowHeight={this.rowHeight}
            rowRenderer={this.rowRenderer}
            onRowsRendered={this.onRowsRendered}
            scrollToAlignment="start"
          />
        )}
      </AutoSizer>
    )
  }

  cityIndexItem = (index) => {
    this.listRef.current.scrollToRow(index)
  }

  renderCityIndex = () => {
    return (
      <div className="index-box">
        { this.state.cityIndex.map((item, index) => {
          return <div key={item} onClick={() => this.cityIndexItem(index)}>
            <span className={this.state.activeItem === index ? 'active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
          </div>
        }) }
      </div>
    )
  }

  render() {
    return (
      <div className="cityList">
        {this.renderHeader()}

        {this.renderCityList()}

        {this.renderCityIndex()}
      </div>
    )
  }

  componentWillUnmount() {
    this.getCityList = null
  }
}
